﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using StockFinder.Model;

namespace StockFinder.Extractors.PremiumData
{
    /// <summary>
    /// Gets list of stocks for PremiumData output
    /// </summary>
    public class PremiumDataStockFilePathsExtractor
    {
        const string DIRECTORY_SEED = @"C:\Trading Data\Formatted Output\";

        public List<string> GetStockFilePaths()
        {
            //1 get files of stocks
            List<string> stockFilePaths = new List<string>();

            Directory.EnumerateDirectories(DIRECTORY_SEED).ToList().ForEach(d => stockFilePaths.AddRange(Directory.EnumerateFiles(d)));

            return stockFilePaths;
        }

        public List<DailyPrice> GetPricesFromFilename(string filename)
        {
            List<DailyPrice> historicPrices = new List<DailyPrice>();

            using (StreamReader sr = new StreamReader(filename))
            {
                string fileContents = sr.ReadToEnd();

                var lines = fileContents.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);                

                string line = string.Empty;

                for (int j = 0; j < lines.Count(); j++)
                {
                    //ignore the first line
                    if (j > 0)
                    {
                        line = lines[j];

                        if (string.IsNullOrEmpty(line)) continue;

                        var cells = line.Split(new string[] { "," }, StringSplitOptions.None);

                        historicPrices.Add(new DailyPrice()
                        {
                            PriceDate = DateTime.ParseExact(cells[0], "yyyyMMdd", null),
                            Open = Convert.ToDecimal(cells[1]),
                            High = Convert.ToDecimal(cells[2]),
                            Low = Convert.ToDecimal(cells[3]),
                            Close = Convert.ToDecimal(cells[4]),
                            AdjustedClose = Convert.ToDecimal(cells[4]),
                            Volume = Convert.ToInt64(cells[5])
                        });
                    }
                }
            }

            return historicPrices;
        }
    }
}
